package com.venus.mq.netty.server;

import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;
import com.google.common.collect.Maps;
import com.venus.mq.model.MqResponse;
import com.venus.mq.model.Topic;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Semaphore;

/**
 * Created by mc on 18/5/29.
 * netty事件处理类
 */
public class NettyServerHandler extends SimpleChannelInboundHandler<Topic> {
    /*
     * 收到消息时，返回信息
     */

    //服务端限流
    private static final Map<String, Semaphore> serviceKeySemaphoreMap = Maps.newConcurrentMap();

    private static final Logger logger = LoggerFactory.getLogger(NettyServerHandler.class);
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Topic topic)
            throws Exception {
        // 收到消息直接打印输出
        System.out.println("服务端接受的消息 : " + topic.toString());
        if (ctx.channel().isWritable()) {
            //从服务调用对象里获取服务提供者信息
            MqResponse mqResponse = new MqResponse();
            mqResponse.setIsSuccess(true);
            //将服务调用返回对象回写到消费端
            ctx.writeAndFlush(mqResponse);
        } else {
            logger.error("------------channel closed!---------------");
        }
    }


     /** 建立连接时，返回消息**/

    /*@Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("连接的客户端地址:" + ctx.channel().remoteAddress());
        ctx.writeAndFlush("客户端"+ InetAddress.getLocalHost().getHostName() + "成功与服务端建立连接！ \n");
        super.channelActive(ctx);
    }*/
}
